package com.canieatit.gwt.server;

import java.net.MalformedURLException;
import java.util.HashMap;
import java.util.Map;
import java.util.logging.Logger;

import redstone.xmlrpc.XmlRpcClient;
import redstone.xmlrpc.XmlRpcException;
import redstone.xmlrpc.XmlRpcFault;

import com.canieatit.gwt.shared.Product;

public class UPCDatabaseChecker {
	
	private static final Logger log = Logger.getLogger(UPCDatabaseChecker.class.getName());
	private final static String RPC_KEY = "b303d064b4fb495aabac51aa44d96f89c40a26f9";

	@SuppressWarnings("unchecked")
	public
	static Product lookup(String format, String value) {
		XmlRpcClient client = null;
		try {
			client = new XmlRpcClient("http://www.upcdatabase.com/xmlrpc", false);
		} catch (MalformedURLException e1) {
			e1.printStackTrace();
		}
		Map<String, String> params = new HashMap<String, String>();
		params.put("rpc_key", RPC_KEY);
		params.put(format, value);
		
	    HashMap<String, ?> token = null;
		try {
			log.info("Calling lookup on UPC Database");
			token = (HashMap<String, ?>) client.invoke( "lookup", new Object[] { params } );
		} catch (XmlRpcException e) {
			e.printStackTrace();
		} catch (XmlRpcFault e) {
			e.printStackTrace();
		}
		
		if (token.get("status").equals("success")) {
			if ((Boolean) token.get("found")) {
				Product product = new Product((String) token.get("ean"), (String)token.get("description"), (String)token.get("issuerCountry"), (String)token.get("size"));
				new DataStore().putToDataStore(product);
				return product;
			}
		} 
		
		return null;
	}
	
	
	
	
}
